package com.itheima.reggie.controller;


import com.itheima.reggie.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
public class FileController {

    @Value("${reggie.file-path}")
    private String path;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/common/upload")
    public R upload(MultipartFile file) {

        try {
            //获取原文件名，切割后缀
            String filename = file.getOriginalFilename();
            String suffix = filename.substring(filename.lastIndexOf("."));

            //UUID构建文件名 防止文件名重复 导致覆盖
            String newName = UUID.randomUUID().toString().replace("-", "") + suffix;

            //准备保持目录 确保有目录存在
            File dir = new File(path);
            if (!dir.exists()) {  //目录不存在
                //创建目录
                dir.mkdirs();
            }

            //保存文件
            File f = new File(path + newName);
            file.transferTo(f);

            //返回文件名给页码
            return R.success(newName);
        } catch (IOException e) {
            e.printStackTrace();

            return R.error("上传文件失败！");
        }
    }

    /**
     * 文件下载
     *
     * @param name
     * @param response
     * @return
     */
    @GetMapping("/common/download")
    public R download(String name, HttpServletResponse response) {

        try {
            //定位文件位置
            File file = new File(path + name);

            //把文件读到缓冲区
            FileInputStream fis = new FileInputStream(file);

            //获取输出流对象
            ServletOutputStream os = response.getOutputStream();

            byte[] bytes = new byte[8192];

            int len = 0;
            while ((len = fis.read(bytes)) != -1) {
                os.write(bytes, 0, len);
                os.flush();
            }

            //关闭流
            os.close();
            fis.close();

            return R.success("下载成功！");
        } catch (IOException e) {
            e.printStackTrace();

            return R.error("下载失败！");
        }
    }
}
